package org.proxywars.engine.rts.units;

import java.util.ArrayList;
import java.util.List;

import org.proxywars.engine.rts.EGroupJoinException;
import org.proxywars.engine.rts.IParty;
import org.proxywars.engine.rts.IUnit;
import org.proxywars.engine.rts.IUnitGroup;

public class UnitGroup implements IUnitGroup {

	private List<IUnit> units = new ArrayList<IUnit>();
	private IParty owner;

	public UnitGroup(IParty owner) {
		if( owner == null )
			throw new IllegalArgumentException("Owner may not be null");
		this.owner = owner;
	}

	@Override
	public void add(IUnit unit) throws EGroupJoinException {
		if( unit.getOwner() == null )
			unit.setOwner(owner);
		if(unit.getOwner().equals(owner))
		{
			if( isUnitAddable(unit) )
				units.add(unit);
		}
		else
			throw new EGroupJoinException(this,unit,"owner of unit != owner of group");
	}

	/**
	 * This method can be overidden to check additional conditions
	 * @param unit
	 * @return
	 */
	protected boolean isUnitAddable(IUnit unit) {
		return true;
	}

	@Override
	public void remove(IUnit unit) {
		units.remove(unit);
	}

	@Override
	public IParty getOwner() {
		return owner;
	}

}
